/**
 * Created by PanJiaChen on 16/11/18.
 */
import Cookies from 'js-cookie'

/**
 * 加载css
 * @param {*} url
 */
export const loadStyle = url => {
  const link = document.createElement('link')
  link.type = 'text/css'
  link.rel = 'stylesheet'
  link.href = url
  const head = document.getElementsByTagName('head')[0]
  head.appendChild(link)
}

/**
 * 获取url中参数对象
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function renderTime(time, cFormat) {
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  const date = parseDate(time)
  if (!date) {
    return null
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 *解析身份证的出生日期和性别
 * @param {身份证号} card
  */
export function getIdCardInfo(card) {
  const birthday = card.substring(6, 10) + '-' + card.substring(10, 12) + '-' + card.substring(12, 14)
  const sex = parseInt(card.substr(16, 1)) % 2 === 1 ? 1 : 2
  return { birthday, sex }
}

/**
 * 根据出生日期计算年龄
 * @param {出生日期} birthday
 */
export function getAgebyBirthday(birthday) {
  var year = parseInt(renderTime(birthday, '{y}') || 0)
  return year === 0 ? 0 : parseInt(renderTime(new Date(), '{y}')) - parseInt(renderTime(birthday, '{y}'))
}

/**
 * 将各种格式的日期转换成js识别的时间
 * @param {*} time
 */
export function parseDate(time) {
  if (!time) { return undefined }
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  return date
}

/**
 * 对象深拷贝
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * 将其他数据类型转换成字符串
 * @param {*} value
 */
export function toString(value) {
  const type = typeof (value)
  if (value != null && value !== undefined) {
    if (type === 'object') {
      return JSON.stringify(value)
    } else if (['number', 'boolean', 'string'].includes(type)) {
      return String(value)
    } else {
      throw new Error('数据类型异常!')
    }
  }
  return ''
}

/**
 * 字符串转换成对象
 * @param {*} value
 */
export function toObject(value) {
  const type = typeof (value)
  if (value != null && value !== undefined) {
    if (type === 'object') {
      return {}
    } else if (['string'].includes(type)) {
      try {
        return JSON.parse(value)
      } catch {
        throw new Error('数据类型转换异常!')
      }
    } else {
      throw new Error('数据类型异常!')
    }
  }
  return {}
}

/**
 * 是否是数组
 * @param {Array} arg
 * @returns {Boolean}
 */
export function isArray(arg) {
  if (typeof Array.isArray === 'undefined') {
    return Object.prototype.toString.call(arg) === '[object Array]'
  }
  return Array.isArray(arg)
}

/**
 * 将字符串转换成base64
 */
export function encode(str) {
  var encode = encodeURI(str)
  var base64 = btoa(encode)
  return base64
}

/**
 * 将base64换成字符串
 */
export function decode(base64) {
  var decode = atob(base64)
  var str = decodeURI(decode)
  return str
}

// 以下是操作cookie方法(高级用法参考:https://github.com/js-cookie/js-cookie#readme)
/**
 * 根据key值获取cookie
 */
export function getCookie(key) {
  return Cookies.get(key)
}

/**
 * 设置cookie
 * options[expires]:有效天数
 * options[path]:该cookie对当前页面的路径有效
 * options[domain]:指定域名下有效.domain.com
 */
export function setCookie(key, value, options = {}) {
  return Cookies.set(key, value, options)
}

/**
 * 删除cookie
 */
export function removeCookie(key) {
  return Cookies.remove(key)
}

/**
 * 设置localStorage
 * @param {*} key
 * @param {*} value
 */
export function setLocalStorage(key, value) {
  localStorage.setItem(key, toString(value))
}

/**
 * 获取localStorage
 * @param {*} key
 */
export function getLocalStorage(key) {
  return localStorage.getItem(key)
}

/**
 * 删除localStorage
 * @param {*} key
 */
export function removeLocalStorage(key) {
  return localStorage.removeItem(key)
}

/**
 * 设置sessionStorage
 * @param {*} key
 * @param {*} value
 */
export function setSessionStorage(key, value) {
  sessionStorage.setItem(key, toString(value))
}

/**
 * 获取sessionStorage
 * @param {*} key
 */
export function getSessionStorage(key) {
  return sessionStorage.getItem(key)
}

/**
 * 删除sessionStorage
 * @param {*} key
 */
export function removeSessionStorage(key) {
  return sessionStorage.removeItem(key)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}
